<template>
  <div class="icon-renderer">
    <!-- FontAwesome 图标 -->
    <font-awesome-icon v-if="isFontAwesomeIcon" :icon="fontAwesomeIconObject" class="iconfont2" />

    <!-- Element Plus 图标 -->
    <el-icon v-else-if="isElementIcon" class="iconfont2">
      <component :is="elementIconComponent" />
    </el-icon>

    <!-- iconfont 图标 -->
    <i v-else-if="isIconfontIcon" :class="iconClass" class="iconfont2"></i>

    <!-- 默认图标 -->
    <i v-else class="iconfont icon-shouye iconfont2"></i>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { fas } from "@fortawesome/free-solid-svg-icons";
import { far } from "@fortawesome/free-regular-svg-icons";
import { fab } from "@fortawesome/free-brands-svg-icons";
import * as ElementIcons from "@element-plus/icons-vue";

interface Props {
  icon?: string;
}

const props = withDefaults(defineProps<Props>(), {
  icon: ""
});

// 判断是否为 FontAwesome 图标
const isFontAwesomeIcon = computed(() => {
  if (!props.icon) return false;
  return props.icon.startsWith("fas ") || props.icon.startsWith("far ") || props.icon.startsWith("fab ");
});

// 获取 FontAwesome 图标对象
const fontAwesomeIconObject = computed(() => {
  if (!isFontAwesomeIcon.value) return ["fas", "question"];

  const [prefix, iconName] = props.icon.split(" ");
  const cleanIconName = iconName.replace("fa-", "");

  if (prefix === "fas") {
    return fas[cleanIconName] || ["fas", "question"];
  } else if (prefix === "far") {
    return far[cleanIconName] || ["far", "question"];
  } else if (prefix === "fab") {
    return fab[cleanIconName] || ["fab", "question"];
  }

  return ["fas", "question"];
});

// 判断是否为 Element Plus 图标
const isElementIcon = computed(() => {
  if (!props.icon) return false;
  return ElementIcons[props.icon as keyof typeof ElementIcons] !== undefined;
});

// 获取 Element Plus 图标组件
const elementIconComponent = computed(() => {
  if (!isElementIcon.value) return null;
  return ElementIcons[props.icon as keyof typeof ElementIcons];
});

// 判断是否为 iconfont 图标
const isIconfontIcon = computed(() => {
  if (!props.icon) return false;
  // 检查是否为 iconfont 或 iconfont2 图标
  return props.icon.startsWith("icon-") || props.icon.includes("iconfont") || props.icon.includes("icon-");
});

// 获取 iconfont 图标类名
const iconClass = computed(() => {
  if (!isIconfontIcon.value) return "";

  // 如果已经是完整的类名，直接返回
  if (props.icon.includes("iconfont")) {
    return props.icon;
  }

  // 如果是 icon- 开头的图标名，添加 iconfont2 类
  if (props.icon.startsWith("icon-")) {
    return `iconfont2 ${props.icon}`;
  }

  return props.icon;
});
</script>

<style lang="scss" scoped>
.icon-renderer {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  .iconfont2 {
    width: 24px;
    font-size: 14px;
    text-align: center;
  }
}
</style>
